<template>
  <div class="print-page" v-loading="loading">
    <div>
      <el-button class="bk-print-button" :theme="'primary'" :title="'打印本页'" @click="doPrint" :disabled="!info.id">
        {{ "打印本页" }}
      </el-button>
    </div>
    <DeathCard v-model="info" ref="deathCard" class="print-area" />
  </div>
</template>


<script>
import { getDetailById } from '@/api/record';
import DeathCard from '@/components/DeathCard';
import { toPng } from 'html-to-image';

export default {
  name: 'PrintDeathCard',
  components: { DeathCard },
  data() {
    return {
      loading: false,
      info: {}
    }
  },
  created() {
    this.getInfo()
  },
  methods: {
    step(time = 0) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve()
        }, time)
      })
    },
    async doPrint() {
      const node = this.$refs.deathCard.$el;
      // 缩放后宽高 这里有做0.85倍缩放
      let { width: viewWidth, height: viewHeight } = node.getBoundingClientRect()
      // 缩放前宽高
      let { width: cssWidth, height: cssHeight } = window.getComputedStyle(node)

      // const offsetX = (Number(cssWidth.slice(0, -2)) - viewWidth) / 2
      // const offsetY = (Number(cssHeight.slice(0, -2)) - viewHeight)

      const dataUrl = await toPng(node)

      document.body.innerHTML = `
        <div style="text-align: center;
                width: 100%;
                display: -webkit-box;
                display: -ms-flexbox;
                display: flex;
                -webkit-box-align: start;
                -ms-flex-align: start;
                align-items: flex-start;
                -webkit-box-pack: center;
                -ms-flex-pack: center;
                justify-content: center;">
            <img src="${dataUrl}" style="width:${viewWidth}px;height:${viewHeight}px;">
         </div>
          `;

      await this.step();
      window.print();
      window.location.reload();
      return false;

    },
    async getInfo() {
      try {
        this.loading = true;
        const { data } = await getDetailById(this.$route.query)
        this.loading = false;
        Object.keys(data).forEach(key => {
          this.$set(this.info, key, data[key])
        })
      } catch (error) {
        this.loading = false;
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@page {
  // size: landscape;
  size: portrait
}

.print-page {
  padding: 20px;
  // display: flex;
  // align-items: flex-start;
  // justify-content: center;
}

.print-area {
  padding: 4px;
  transform: scale3D(0.85, 0.85, 1);
  transform-origin: center top;
}
</style>
